//
//  NSString+MD5.m
//  Cunli
//
//  Created by lilubin on 15/6/1.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "NSString+MD5.h"
#import <CommonCrypto/CommonDigest.h>
#define PRIVATEKEY @"D2F56EAFBQ"

@implementation NSString (MD5)

/*
 *function:将传入对dictionary按照key进行生序排列，按照key1value1key2value2...的方式进行拼接，返回字符串
 *dict:传入的字典
 *result:返回拼接好的字符串
 */
+ (NSString *)sortDictToMD5StrWithDict:(NSDictionary *)dict
{
    NSString *resultStr = [[NSString alloc] init];
    NSArray *sortArray = [dict allKeys];
    NSArray *resultArray = [sortArray sortedArrayUsingSelector:@selector(compare:)];
    for (int i = 0; i < resultArray.count; i++) {
        resultStr = [resultStr stringByAppendingFormat:@"%@%@", resultArray[i], [dict objectForKey:resultArray[i]]];
    }
    return resultStr;
}

/*
 *function:md5加密程序，输出32位小写
 *input:待加密字符串
 *output:加密完成的字符串，输出32位小写
 */
+ (NSString *)md5HexDigest:(NSString *)input
{
    const char* cStr = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [ret appendFormat:@"%02x", result[i]];
    }
    return ret;
}


/*
 * function:根据参数获取签名，params的key，value按照生序排列，拼接PRIVATEKEY之后，进行md5加密，生成sign;
 * params:字典形式的参数;
 * result:返回md5加密的sign;
 */
+ (NSString *)getSignFromParam:(NSDictionary *)params
{
    NSMutableString *dictStr = [[NSString sortDictToMD5StrWithDict:params] mutableCopy];
    [dictStr appendString:PRIVATEKEY];
    NSString *signStr = [NSString md5HexDigest:dictStr];
    return signStr;
}

/*
 *fun: 获取有session参与的签名
 *params: 获取签名需要的字典参数  session:获取签名需要的session
 *result: 返回签名字符串
 */
+ (NSString *)getSignFromParam:(NSDictionary *)params andSession:(NSString *)session
{
    NSString *sign = [NSString getSignFromParam:params];
    NSString *signAndSession = [sign stringByAppendingString:session];
    NSString *resultSign = [NSString md5HexDigest:signAndSession];
    return resultSign;
}

+ (BOOL)theMaxString:(NSString *)maxStr containSpecificCharacter:(NSString *)str
{
    if ([maxStr rangeOfString:str].length != 0) {
        return YES;
    }
    return NO;
}



@end
